package com.mingzhi.forum.service.impl;

import com.mingzhi.forum.common.AppResult;
import com.mingzhi.forum.common.ResultCode;
import com.mingzhi.forum.dao.UserMapper;
import com.mingzhi.forum.exception.ApplicationException;
import com.mingzhi.forum.model.Article;
import com.mingzhi.forum.model.Board;
import com.mingzhi.forum.model.User;
import com.mingzhi.forum.service.IUserService;
import com.mingzhi.forum.utils.MD5Util;
import com.mingzhi.forum.utils.StringUtil;
import com.mingzhi.forum.utils.UUIDUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class UserServiceImpl implements IUserService {
    @Resource
    private UserMapper userMapper;

    /**
     * 实现 普通用户的创建
     *
     * @param user 传入的参数
     */
    @Override
    public void createNormalUser(User user) {

        //先进行校验
        if (user == null) {
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }

        //查询当前用户是否存在  exist 存在
        User existUser = userMapper.selectUserByName(user.getUsername());
        if (existUser != null) {
            //打印日志
            log.info(ResultCode.FAILED_CREATE.toString() + "username = " + user.getUsername());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }

        //除了传进来时的有效值，其他全部使用默认，虽然数据库里面设置的有默认值，但是尽量使用代码控制
        if (user.getGender() == null) {
            user.setGender((byte) 2);
        }
        user.setIsAdmin((byte) 0);//是否是管理员 0 否
        user.setAvatarUrl(null);//用户头像路径
        user.setArticleCount(0);//发帖数量
        user.setState((byte) 0);//状态 0 正常
        user.setDeleteState((byte) 0);//是否删除 0 否
        Date date = new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);

        //新增用户
        int row = userMapper.insertSelective(user);
        if (row != 1) {
            //打印日志
            log.info(ResultCode.FAILED_CREATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }

        //新增成功日志
        log.info("新增用户成功：username = " + user.getUsername());

    }

    /**
     * 根据用户名查询用户
     *
     * @param username 用户名
     * @return
     */
    @Override
    public User selectUserByName(String username) {
        //非空校验（前端登录的时候，肯定会校验，但是为了代码的健壮性，这里加上）
        if (StringUtil.isEmpty(username)) {
            //打印日志
            log.info("用户名：" + ResultCode.ERROR_IS_NULL.getMessage());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        return userMapper.selectUserByName(username);
    }

    /**
     * 用户登录
     *
     * @param username 前端传的用户名
     * @param password 前端传的密码
     * @return
     */
    @Override
    public User login(String username, String password) {

        //非空校验
        if (StringUtil.isEmpty(username) || StringUtil.isEmpty(password)) {
            //打印日志
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }

        //根据用户名来获取用户信息
        User user = selectUserByName(username);
        //对查询结果进行非空校验
        if (user == null) {
            //打印日志
            log.info(ResultCode.FAILED_LOGIN.toString() + ",username = " + username);
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        //对密码进行校验
        String encryptPassword = MD5Util.md5Salt(password, user.getSalt());
        if (!encryptPassword.equals(user.getPassword())) {
            //打印日志
            log.info(ResultCode.FAILED_LOGIN.toString() + ",密码错误,username = " + username + ",password = " + password);
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        //登录成功，返回用户信息
        return user;
    }

    /**
     * 根据用户id来查询用户信息
     *
     * @return
     */
    @Override
    public User selectById(Long Id) {
        //进行非空校验
        if (Id == null) {
            //打印日志
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        User user = userMapper.selectByPrimaryKey(Id);
        return user;
    }

    /**
     * 更新用户的发帖数
     *
     * @param id
     */
    @Override
    public void addOneArticleCountById(Long id) {
        //进行校验
        if (id == null || id <= 0) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //调用service层进行查询
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null) {
            //打印日志
            log.warn(ResultCode.ERROR_IS_NULL.toString() + ", user id = " + id);
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        //更新用户帖子数量
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount() + 1);
        int userRow = userMapper.updateByPrimaryKeySelective(updateUser);
        if (userRow != 1) {
            //打印日志
            log.warn(ResultCode.FAILED.toString() + ", 受影响行数不等于1");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void subOneArticleCountById(Long id) {
        //进行校验
        if (id == null || id <= 0) {
            //打印日志 用户帖子数量更新失败
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }
        //根据用户id进行板块查询
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null) {
            //打印日志 用户不存在
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString() + ", user id = " + id + " .");
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //构造用户对象
        User updateUser = new User();

        updateUser.setId(id);//用户id
        updateUser.setArticleCount(user.getArticleCount() - 1);//在用户原本的帖子数量上减一
        //进行帖子数量判断 看减一之后是否为负数
        if (updateUser.getArticleCount() < 0) {
            updateUser.setArticleCount(0);
        }
        //将这个新的更新对象写道数据库
        int updateUserRow = userMapper.updateByPrimaryKeySelective(updateUser);
        //进行执行结果判断
        if (updateUserRow != 1) {
            //打印日志
            log.warn(ResultCode.FAILED.toString() + ", 受影响行数不等于1 .");
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void modifyInfo(User user) {
        if (user == null || user.getId() == null || user.getId() <= 0) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //校验用户是否存在
        User existsUser = userMapper.selectByPrimaryKey(user.getId());
        if (existsUser == null) {
            //打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        //开始校验里面的每个参数
        //定义一个标志位
        boolean checkAttr = false; //为false 表示没有校验通过
        //定义一个更新对象
        User updateUser = new User();
        //设置用户id
        updateUser.setId(user.getId());

        //对每个参数进行非空校验
        if (!StringUtil.isEmpty(user.getUsername())
                && !user.getUsername().equals(existsUser.getUsername())) {
            //更新用户名(登录名)
            User checkUser = userMapper.selectUserByName(user.getUsername());
            if (checkUser != null) {
                //打印日志
                log.warn(ResultCode.AILED_USER_EXISTS.toString());
                //抛出异常
                throw new ApplicationException(AppResult.failed(ResultCode.AILED_USER_EXISTS));
            }
            updateUser.setUsername(user.getUsername());
            //更新标志位
            checkAttr = true;
        }

        //校验昵称
        if (!StringUtil.isEmpty(user.getNickname())
                && !user.getNickname().equals(existsUser.getNickname())) {
            updateUser.setNickname(user.getNickname());
            //更新标志位
            checkAttr = true;
        }

        //校验性别
        if (user.getGender() != null
                && user.getGender() != existsUser.getGender()) {
            updateUser.setGender(user.getGender());
            //合法性校验
            if (updateUser.getGender() > 2 || updateUser.getGender() < 0) {
                updateUser.setGender((byte) 2);
            }
            //更新标志位
            checkAttr = true;
        }

        //校验邮箱
        if (!StringUtil.isEmpty(user.getEmail())
                && !user.getEmail().equals(existsUser.getEmail())) {
            updateUser.setEmail(user.getEmail());
            //更新标志位
            checkAttr = true;
        }

        //校验电话号码
        if (!StringUtil.isEmpty(user.getPhoneNum())
                && !user.getPhoneNum().equals(existsUser.getPhoneNum())) {
            updateUser.setPhoneNum(user.getPhoneNum());
            //更新标志位
            checkAttr = true;
        }

        //校验个人简介
        if (!StringUtil.isEmpty(user.getRemark())
                && !user.getRemark().equals(existsUser.getRemark())) {
            updateUser.setRemark(user.getRemark());
            //更新标志位
            checkAttr = true;
        }

        //根据标志位来判断是否可以执行
        if (checkAttr == false){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //调用mapper
        int i = userMapper.updateByPrimaryKeySelective(updateUser);
        if(i != 1){
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString() + ", 受影响的行数不为1");
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void modifyPassword(Long id, String newPassword, String oldPassword) {
        //进行非空校验
        if(id == null || id <= 0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //根据用户id查询用户信息
        User user = userMapper.selectByPrimaryKey(id);
        if(user == null || user.getDeleteState() == 1){
            //打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //校验原密码是否正确
        String oldEncryptPassword = MD5Util.md5Salt(oldPassword, user.getSalt());
        if(!oldEncryptPassword.equals(user.getPassword())){
            //打印日志 原密码不正确
            log.warn(ResultCode.INCORRECT_PASSWORD.toString() + "username = " + user.getUsername() + "，password = " + oldPassword);
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.INCORRECT_PASSWORD));
        }
        //重新生成盐
        String salt = UUIDUtil.UUID_32();
        //计算出新的密码
        String encryptPassword = MD5Util.md5Salt(newPassword, salt);
        //构建出一个新的对象
        User modifyUser = new User();
        //设置用户id
        modifyUser.setId(user.getId());
        //设置新的密码
        modifyUser.setPassword(encryptPassword);
        //设置新的盐
        modifyUser.setSalt(salt);
        //设置更新时间
        modifyUser.setUpdateTime(new Date());

        //调用mapper层
        int i = userMapper.updateByPrimaryKeySelective(modifyUser);
        if(i != 1){
            //打印日志
            log.warn(ResultCode.FAILED.toString() + ", 受影响行数不等于1 .");
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
        //打印日志
        log.info("用户密码修改成功：" + user.getUsername());
    }
}
